package com.farah.lease.web.app.custom.interceptor;

import com.farah.lease.common.login.LoginUser;
import com.farah.lease.common.login.LoginUserHolder;
import com.farah.lease.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @Author 不爱跑步的法拉韶
 * @Date 2024-07-01__07:57
 * @Description 拦截器
 **/
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    // 在请求处理之前进行调用(Controller方法调用之前)
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("access-token");
        Claims claims = JwtUtil.parseToken(token);
        Long userId = claims.get("userId", Long.class);
        String username = claims.get("username", String.class);
        LoginUserHolder.setLoginUser(new LoginUser(userId, username));
        return true;
    }

    // 请求处理之后进行调用，但是在视图被渲染之前(Controller方法调用之后)
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LoginUserHolder.clear();
    }


}
